﻿var express = require('express');
var app =express();
var https = require('https');
var bodyParser = require('body-parser');
var fs = require('fs');
const root = '../images/';
var imgHash = require('./imghash1.js');
var searchImg = require("./searchImg.js");
var multiparty = require('multiparty'); 
var compressImg = require('./compressImages.js');
// 添加json解析
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
//设置跨域访问
app.all('*', function(req, res, next) {
	res.header("Access-Control-Allow-Origin", "*");
	res.header("Access-Control-Max-Age", "3600");
	res.header("Content-Type", "application/x-www-form-urlencoded");
	res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
	res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
	res.header("X-Powered-By", ' 3.2.1');
	next();
});
//const options = {
//	key: fs.readFileSync('../SL/214915726350840.key', 'utf8'),
//	cert: fs.readFileSync('../SL/214915726350840.pem', 'utf8')
//};
//const options = {
//	pfx: fs.readFileSync('../SL/214915726350840.pfx', 'utf-8'),
//	passphrase: 'alias'
//};
const port = 6777;
const SSL_PORT = 443;
//配置服务端口
//https.createServer(options, app).listen(port, function() {
//	console.log('Listening at https:localhost:' + port);
//});
var server = app.listen(6777, function() {
	console.log('Listening at https:localhost:' + port);
})

//const dbConfig = {
//	host: 'bdm281669391.my3w.com',
//	port: 3306,
//	user: 'bdm281669391',
//	password: 'Xnqpfwyd5',
//	database: 'bdm281669391_db',
//	insecureAuth: true 
//};

const dbConfig = {
	host: 'localhost',
	port: 3307,
	user: 'root',
	password: 'Xnqpfwyd5',
	database: 'imgnet',
	insecureAuth: true 
};

var mysql = require('mysql');
var pool = mysql.createPool(dbConfig);
function getyyyyMMdd(d) {
	var curr_date = d.getDate();
	var curr_month = d.getMonth() + 1;
	var curr_year = d.getFullYear();
	String(curr_month).length < 2 ? (curr_month = "0" + curr_month) : curr_month;
	String(curr_date).length < 2 ? (curr_date = "0" + curr_date) : curr_date;
	var yyyyMMdd = curr_year + "" + curr_month + "" + curr_date;
	return yyyyMMdd;
}
//Login API
app.post('/api/login', function(req, res) {
	console.log("--------Login API : " + req.body.username + "--------");
	var name = req.body.username,
		psw = req.body.password,
		qqLogin = req.body.qqLogin,
		query = "SELECT * FROM `" + dbConfig.database + "`.`user` where `name`='" + name + "'";
	pool.getConnection(function(err, connection) {
		connection.query(query, function(error, results, fields) {
			if(error) throw error;
			if (results.length <= 0) {
				if (qqLogin) {
					pool.getConnection(function(err, connection) {
						var role = 1;
						var lastlogin = getyyyyMMdd(new Date());
						connection.query("insert `user`(`name`,`role`,`password`,`lastlogin`) values('" + name + "'," + role + ",'" + psw + "','" + lastlogin + "')", function(error, results, fields) {
							if(error) throw error;
							res.status(200).send("Register Success!");
							connection.release();
						});
					});
				} else {
					res.status(500).send('用户名或密码错误！');
					console.log(name + " 用户名或密码错误！");
				}
			} else {
				if (results[0].password === psw) {
					
					pool.getConnection(function(err, connection) {
						var lastlogin = getyyyyMMdd(new Date());
						var user = results[0];
						var q = "update `user` set `lastlogin`='" + lastlogin + "' where `id`=" + results[0].id;
						connection.query(q, function(error, results, fields) {
							if(error) throw error;
							console.log(results[0]);
							res.status(200).send(user);
							console.log(name + " 用户登录成功！");
							connection.release();
						});
					});
					
				} else {
					res.status(500).send('用户名或密码错误！');
					console.log(name + " 用户名或密码错误！");
				}
			}	
			connection.release();
		});
	});
});

//collection operation
//1. add new collection
app.post('/api/collections', function(req, res) {
	console.log("--------Get User Collections: " + req.body.id + "--------");
    var id = req.body.id,
    cname = req.body.cname;
    pool.getConnection(function(err, connection) {
    	connection.query("insert `collections_users`(`cname`,`user_id`) values('" + cname + "'," + id + ")", function(error, results, fields) {
    		if(error) throw error;
    		res.status(200).send("Add Collection Success!");
    		connection.release();
    	});
    });
   
});

app.delete('/api/collections/:cname', function(req, res) {
	console.log("--------Get Original Collections: " + req.params.cname + "--------");
    var cname = req.params.cname;
    pool.getConnection(function(err, connection) {
    	connection.query("delete from `collections_users` where `cname` = '" + cname + "'", function(error, results, fields) {
    		if(error) throw error;
    		res.status(200).send("Delete Collection Success!");
    		connection.release();
    	});
    });
   
});

//2. get collections
app.get('/api/collections', function(req, res) {

	var files = fs.readdirSync('../images');
	var r = [];
	for(var i = 0; i < files.length; i++) {
		var dir = fs.readdirSync('../images/' + files[i]);
		r.push({
			cname: files[i],
			cover: dir[dir.length - 2]
		});
	}
	res.status(200).send(r);

});
var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var ascMap = new Map();
var start = 0;
var delta = i;
for(var i = 0; i < alphabet.length; i++) {
	var c = alphabet.charAt(i);

	if(c == 'A') {
		start = 65;
		delta = 0;
	} else if(c == 'a') {
		start = 97;
		delta = 0;
	} else if(c == '0') {
		start = 48;
		delta = 0;
	}

	ascMap.set(c, start + delta);
	delta++;
}
/**
 * Quick Sort
 * @param {Object} array
 * @param {Object} left
 * @param {Object} right
 * @param {Object} arr
 */
var quick = function(array, left, right, arr) {
	var index;
	if(array.length > 1) {
		index = partition(array, left, right, arr);

		if(left < index - 1) {
			quick(array, left, index - 1, arr);
		}

		if(index < right) {
			quick(array, index, right, arr);
		}
	}
}

var partition = function(array, left, right, arr) {
	var pivot = array[Math.floor((right + left) / 2)],
		i = left,
		j = right;
	while(i < j) {
		while(array[i] < pivot) {
			i++;
		}

		while(array[j] > pivot) {
			j--;
		}

		if(i <= j) {
			swap(array, i, j, arr);
			i++;
			j--;
		}
	}
	return i;
}

var swap = function(array, i, j, arr) {
	var temp = array[j];
	array[j] = array[i];
	array[i] = temp;
	var otemp = arr[j];
	arr[j] = arr[i];
	arr[i] = otemp;
}



app.get("/api/collections/:cname/images", function(req, res) {
	console.log(req.params);
	var dirName = req.params.cname;
	fs.readdir('../images/' + dirName, function(err,files){  
    	if(err){  
        	return console.error(err);  
    	}
    	var arr = files;
    	var t = [];
    	var reg = new RegExp(/[A-Za-z]/g);
    	for(var i = 0; i < arr.length; i++) {
    		var endIndex = arr[i].indexOf(")");
    		var s = arr[i].substring(0, endIndex);
    		s = s.replace("(", "").replace("QD", "");
    		var n = s.search(reg);
    		var l = s.charAt(n);
    		s = s.substring(n);
    		s = s.replace(l, ascMap.get(l));
    		t.push(parseInt(s));
    	}
    	quick(t, 0, arr.length - 1, arr);
    	res.status(200).send(arr);
	});  

});

/**
 * Register API
 */
app.post('/api/register', function(req, res) {
	var username = req.body.username,
	    pwd = req.body.password,
	    role = 2,
	    query = "SELECT * FROM `" + dbConfig.database + "`.`user` where `name`='" + name + "'";
	pool.getConnection(function(err, connection) {
		connection.query("insert `user`(`name`,`role`,`password`) values('" + username + "'," + role + ",'" + pwd + "')", function(error, results, fields) {
			if(error) throw error;
			res.status(200).send("Register Success!");
			connection.release();
		});
	});
});
/**
 * Get user collections
 */
app.post('/api/users/collections', function(req, res) {
	console.log("--------Get user collections: " + req.body.id + "--------");
    var id = req.body.id;
        pool.getConnection(function(err, connection) {
        	connection.query("SELECT `cname`  FROM `" + dbConfig.database + "`.`collections_users` where `user_id` = " + id, function(error, results, fields) {
        		if(error) throw error;
        		res.status(200).send(results);
        		connection.release();
        	});
        });
	
});
app.get('/api/compress/:cname', function(req, res) {
	var set = req.params.cname;
	fs.readdir('../images/' + set, function(err,files){  
    	if (err){  
        	res.status(500).send(set + "不存在！"); 
        	return;
    	}
    	var hashPath = "../images_hash",
    		minPath = "../images_min";
    	fs.access(minPath + "/" + set, fs.constants.F_OK, (err) => {
    		console.log(err ? set + '文件夹不存在' : set + '文件夹已经存在');
    		if (err) {
    			fs.mkdirSync(minPath + "/" + set);
    		}
    		compressImg.compress(set, files, 0, hashPath, minPath);
    		res.status(200).send(set + "图片处理完毕");
    	});
    	
		
	});
});
app.post('/api/recordset', function(req, res) {
	var cname = req.body.set,
		base = "insert ignore `images`(`img_name`,`cname`, `pixel`) values ?", //如果有重复的会跳过
		query = "",
		baseUrl = '../images/' + cname,
		values = [];
	fs.access(baseUrl, fs.constants.F_OK, (err) => {
		
    	console.log(err ? cname + '文件夹不存在' : cname + '文件夹已经存在');
    	if (err) {
    		res.status(403).send(cname + "文件夹不存在！");
    		return;
    	}
    	var files =  fs.readdirSync(baseUrl);
    	if(files.length > 0) {
    		console.log("=====Record Sets:=====" + cname);
    		for(var j = 0; j < files.length; j++) {
    			var s = files[j].replace(".jpg", "");
    			var p = '';
    			var endIndex = files[j].indexOf(')');
    			if(endIndex >= 0 && endIndex < files[j].length - 1) {
    				p = files[j].substring(endIndex + 1).replace(".jpg", '');
    			} else if(endIndex == files[j].length - 1) {
    				p = ' ';
    			}
    			values.push([s, cname, p]);
    		}
    		//		values.sort(function(a, b) {
    		//			a = a[0];
    		//			b = b[0];
    		//			var endIndex = a.indexOf(')');
    		//			a = a.substring(0, endIndex);
    		//			a = a.replace('QD', '').replace('(', '');
    		//			var endIndex2 = b.indexOf(')');
    		//			b = b.substring(0, endIndex2);
    		//			b = b.replace('QD', '').replace('(', '');
    		//			return a.localeCompare(b);
    		//		})
    		console.log(cname + "==========sort ok!=========");
    		pool.getConnection(function(err, connection) {
    			connection.query(base, [values], function(error, results, fields) {
    				if(error) throw error;
    				res.status(200).send("录入成功!");
    				connection.release();
    			});
    		});
    	} else {
    		res.status(403).send(cname + "文件夹下 无图片！");
    		return;
    	}	
    });
		
		
});

var updateID = function(res, iid, cname) {
	pool.getConnection(function(err, connection) {
		connection.query("update `" + dbConfig.database + "`.`collections_users` set `i_ids` = '" + iid + "' where `cname`= '" + cname + "'", function(error, results, fields) {
			if(error) throw error;
			res.status(200).send("采集成功！");
			connection.release();
		});
	});							
}

app.post('/api/images/bind', function(req, res) {
	var iname = req.body.iname.replace(".jpg", ""),
		cname = req.body.cname,
		sid = req.body.sid || false;
		
	if (!sid) {
		pool.getConnection(function(err, connection) {
			connection.query("SELECT `id` FROM `" + dbConfig.database + "`.`images` where `img_name`= '" + iname + "'", function(error, results, fields) {
				if(error) throw error;
				var iid = -1;
				if(results.length > 0) {
					iid = results[0].id;
					connection.release();
					pool.getConnection(function(err, connection) {
						connection.query("SELECT `i_ids` FROM `" + dbConfig.database + "`.`collections_users` where `cname` = '" + cname + "'", function(error, results, fields) {
							if(error) throw error;
							connection.release();
							if(results[0].i_ids === null) {
								updateID(res, iid, cname);
							} else {
								var arr = results[0].i_ids.split(","),
									index = -1;
								for(var i = 0; i < arr.length; i++) {
									if(arr[i] == parseInt(iid)) {
										res.status(500).send("该图片已采集！");
										index = i;
										break;
									}
								}
								if(index < 0) {
									results[0].i_ids += "," + iid;
									updateID(res, results[0].i_ids, cname);
								}
							}
						});
					});
				} else {
					res.status(500).send("该图片未入库！");
				}
			});
		});
	} else {
		updateID(res, sid, cname);
	}

});


app.get('/api/users/collections/:cname/imageids', function(req, res) {
    var cname = req.params.cname;
    console.log("Get User Images: " + cname );
    pool.getConnection(function(err, connection) {
    	connection.query("SELECT `i_ids` FROM `" + dbConfig.database + "`.`collections_users` where `cname` = '" + cname + "'", function(error, results, fields) {
    		if(error) throw error;
    		res.status(200).send(results);
    		connection.release();
    	});
    });
});

app.post('/api/users/collections/images', function(req, res) {
    var ids = req.body.idarr;
    pool.getConnection(function(err, connection) {
    	connection.query("SELECT * FROM `" + dbConfig.database + "`.`images` where `id` in (?) ", [ids], function(error, results, fields) {
    		if(error) throw error;
    		res.status(200).send(results);
    		connection.release();
    	});
    });    
});
var num = 0;
app.post('/api/search', function(req, res) {
    var form = new multiparty.Form();
    form.parse(req, function(err, fields, files) {
        var hashTemp = imgHash.hash(files.image[files.image.length - 1].path);
        var r = searchImg.searchRun(hashTemp, num);
            num++;
            r.then(results => {
          	res.status(200).send(results);
          });
        
    });

});
